<template>
	<div class="page">
    <div class="user-main">
      <div class="user-header" >
        <el-collapse style="width: 100%;">
          <el-collapse-item title="高级查询" >
            <el-form :inline="true" :model="formInline" class="demo-form-inline" style="padding-left: 10px">
              <el-form-item label="姓名">
                <el-input v-model="formInline.user" placeholder="用户名" size="small"></el-input>
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formInline.email" placeholder="邮箱" size="small"></el-input>
              </el-form-item>
              <el-form-item label="日期">
                <el-date-picker
                  v-model="formInline.searchDate"
                  type="daterange"
                  align="right"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions2" size="small">
                </el-date-picker>
              </el-form-item>
              <el-form-item style="float: right">
                <el-button class="el-main-color"  @click="searchUser" size="small">查 询</el-button>
              </el-form-item>
            </el-form>
          </el-collapse-item>
        </el-collapse>

      </div>
      <div class="user-header">
        <el-button class="el-main-color"  @click="addUser()" size="small">新增用户</el-button>
      </div>
      <!--表格-->
      <el-table :data="tableData" border style="width: 100%;">
        <el-table-column type="index" label="序号" width="50" >
        </el-table-column>
        <el-table-column prop="userCode" label="登录账号" width="180">
        </el-table-column>
        <el-table-column prop="userName" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="state" label="启用" width="50">
        </el-table-column>
        <el-table-column sortable prop="creatDate" label="创建日期" width="180">
        </el-table-column>
        <el-table-column prop="creatBy" label="管理员" width="80">
        </el-table-column>
        <el-table-column prop="remark" label="备注">
        </el-table-column>
        <el-table-column  label="操作" width="150">
          <template slot-scope="scope">
            <el-button @click="addUserRole(scope.row)" type="text" size="mini">角色</el-button>
            <el-button @click="editUser(scope.row)" type="text" size="mini">编辑</el-button>
            <el-button @click="deleteUser(scope.row)"  type="text" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="新增用户" :visible.sync="dialogUserVisible"  :before-close="beforClose">
        <el-form class="demo-ruleForm" :model="user" ref="user" label-width="80px"  style="text-align: left" status-icon :rules="rules1">
          <el-form-item label="登录账号" prop="userCode">
            <el-input  v-model="user.userCode"></el-input>
          </el-form-item>
          <el-form-item label="用户姓名" prop="userName">
            <el-input  v-model="user.userName"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input type="password" v-model="user.password" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPas">
            <el-input type="password" v-model="user.checkPas" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="emil"
                :rules="[
                      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
               ]">
            <el-input type="email" v-model="user.emil"></el-input>
          </el-form-item >
          <el-form-item label="是否使用" prop="status">
            <el-switch
              v-model="user.status"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item >
          <el-form-item label="添加备注" prop="remark">
            <el-input type="textarea" rows="4" placeholder="用户备注信息" v-model="user.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm('user')" size="small" :loading="newSaveButtonStatus">提 交</el-button>
          <el-button @click="resetForm('user')" size="small">重 置</el-button>
        </div>

      </el-dialog>
      <el-dialog title="用户配置角色" :visible.sync="dialogUseRoleVisible">
        <el-form class="demo-ruleForm" :model="userRole" ref="userRole" label-width="80px" style="text-align: left" status-icon>
          <el-form-item label="登录账号" prop="userCode">
            <el-input v-model="userRole.userCode" ></el-input>
          </el-form-item>
          <el-form-item label="配置角色" prop="roleIds">
            <el-select
              v-model="userRole.roleIds"
              multiple
              filterable
              allow-create
              default-first-option
              @visible-change="visibleChange"
              placeholder="请选择文章标签">
              <el-option
                v-for="item in options"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitUserRole('userRole')" size="small" :loading="newSaveButtonStatus">提 交</el-button>
          <el-button @click="resetForm('userRole')" size="small">重 置</el-button>
        </div>
      </el-dialog>
      <!--修改用户信息弹框-->
      <el-dialog title="用户信息修改" :visible.sync="dialogEditUserVisible">
        <el-form class="demo-ruleForm" :model="editUserObj" ref="editUserObj" label-width="80px"  style="text-align: left" status-icon :rules="rules2">
          <el-form-item label="登录账号" prop="userCode">
            <el-input  v-model="editUserObj.userCode"></el-input>
          </el-form-item>
          <el-form-item label="用户姓名" prop="userName">
            <el-input  v-model="editUserObj.userName"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input type="password" v-model="editUserObj.password" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPas">
            <el-input type="password" v-model="editUserObj.checkPas" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="emil"
                        :rules="[
                      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
               ]">
            <el-input type="email" v-model="editUserObj.emil"></el-input>
          </el-form-item >

          <el-form-item label="是否使用" prop="status">
            <el-switch
              v-model="editUserObj.status"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item >
          <el-form-item label="添加备注" prop="remark">
            <el-input type="textarea" rows="4" placeholder="用户备注信息" v-model="editUserObj.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitEditForm('editUserObj')" size="small" :loading="newSaveButtonStatus">提 交</el-button>
          <el-button @click="resetForm('editUserObj')" size="small">重 置</el-button>
        </div>

      </el-dialog>
      <div class="user-header">
        <div class="block">
          <el-pagination :current-page.sync="itemCurrentPage" :page-sizes="itemPageSizes" :page-size="itemPageSize" layout="sizes, prev, pager, next" :total="itemTotal">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>

</template>
<style>
	@import url("../../common/common.css");
	@import url("user.css");
</style>
<script>
	import $ from 'jquery'
  import ElFormItem from "element-ui/packages/form/src/form-item";
  import ElDialog from "element-ui/packages/dialog/src/component";
  import ElInput from "element-ui/packages/input/src/input";
	export default {
    components: {
      ElInput,
      ElDialog,
      ElFormItem},
    data() {
      var checkEditUserCode = (rule,value,callback) =>{
          if (value === '') {
            return callback(new Error('用户昵称不能为空'));
          }
          var _self = this;
          _self.utils.ajaxJSON({
            type: 'POST',
            url: 'user/code',
            data: {
              userCode: _self.editUserObj.userCode
            },
            success: function (res) {

              if (res.status == 200) {
                return callback(new Error('用户昵称已经存在'));
              }
              callback();
            }
          })
      };
      var checkUserCode = (rule,value,callback)=>{
        if (value === '') {
          return callback(new Error('用户昵称不能为空'));
        }
        var _self = this;
        _self.utils.ajaxJSON({
          type:'POST',
          url:'user/code',
          data:{
            userCode:_self.user.userCode
          },
          success:function(res){

          if(res.status == 200){
            return callback(new Error('用户名已经存在'));
          }
            callback();
          }
        })

      };
      var checkAge = (rule, value, callback) => {
        if (value === '') {
          return callback(new Error('年龄不能为空'));
        }
        callback();
      };
      var validatePassEdit =  (rule, value, callback) =>{
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {

          if (this.editUserObj.checkPas !== '') {
            this.$refs.editUserObj.validateField('checkPas');
          }
          callback();
        }
      };
      var validatePass2Edit =  (rule, value, callback) =>{
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.editUserObj.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      var validatePass =  (rule, value, callback) =>{
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {

          if (this.user.checkPas !== '') {
            this.$refs.user.validateField('checkPas');
          }
          callback();
        }
      };
      var validatePass2 =  (rule, value, callback) =>{
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.user.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };

      return {
        itemTotal:5,
        itemCurrentPage:1,
        itemPageSize:5,
        itemPageSizes:[5, 10, 15, 20],
        dialogUserVisible: false,
        dialogEditUserVisible:false,
        newSaveButtonStatus: false,
        dialogUseRoleVisible:false,
        options:[],
        tableData: [],
        userRole:{
          userCode:'',
          userId:'',
          roleIds:[]
        },
        user:{
          userCode:'',
				  userName:'',
          emil:'',
          password:'',
          remark:'',
          checkPas:'',
          status:true,
          roles:[]
        },
        editUserObj:{
          id:'',
          userCode:'',
          userName:'',
          emil:'',
          password:'',
          remark:'',
          checkPas:'',
          status:''
        },
        rules2: {
          userCode:[
            {required: true,validator: checkEditUserCode, trigger:['blur','change']}
          ],
          password: [
            {required: true, validator: validatePassEdit, trigger: 'blur' }
          ],
          checkPas: [
            {required: true, validator: validatePass2Edit, trigger: 'blur' }
          ],
          emil: [
            { validator: checkAge, trigger: 'blur' }
          ],
          userName: [
            { required: true,validator: checkAge, trigger: 'blur'}
          ]
        },
        rules1: {
          userCode:[
            {required: true,validator: checkUserCode, trigger:['blur','change']}
            ],
          password: [
            {required: true, validator: validatePass, trigger: 'blur' }
          ],
          checkPas: [
            {required: true, validator: validatePass2, trigger: 'blur' }
          ],
          emil: [
            { validator: checkAge, trigger: 'blur' }
          ],
          userName: [
            {required: true, validator: checkAge, trigger: 'blur'}
          ]
        },
        /*****搜索表单******/
        formInline: {
          user: '',
          email: '',
          searchDate: ''
        },
        /*******日历控件******/
        pickerOptions2: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
			}
		},
		created() {
      this.requestUserList();
    },
		mounted() {

    },
		methods: {

      visibleChange:function(open){
        var _self = this;
        if(open){
          _self.utils.ajaxJSON({
            type:"post",
            url:'role/loginAll',
            data:{

            },
            success:function(res){
              console.log(res);
              if(res.status  == 200){
                _self.options = res.dataList;
              }

            }
          })
        }
      },
       beforClose:function (done){

        this.resetForm("user");
        done();
      },
      /**
       *  新增用户
       */
      addUser:function(){
        this.dialogUserVisible = true;

      },
      /**
       * 提交新增用户
       */
    submitForm:function(fromName){
        var  _self = this;
        _self.$refs[fromName].validate((valid) => {
          if (valid) {
            _self.utils.ajaxJSON({
              type:'POST',
              url:'userManager/creat',
              data:{
                userCode:_self.user.userCode,
                userName:_self.user.userName,
                emil:_self.user.emil,
                password:_self.user.password,
                remark:_self.user.remark,
                status:_self.user.status
              },
              success:function(res){
                if(res.status == 200){
                  _self.resetForm("user");
                   _self.dialogUserVisible = false;
                  _self.requestUserList();

                }else{

                }
              }
            })

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      /**
       *  提交用户修改信息
       *  @param fromName 表单名
       */
      submitEditForm:function(fromName){
        var  _self = this;
        _self.$refs[fromName].validate((valid) => {
          if (valid) {
            _self.utils.ajaxJSON({
              type:'POST',
              url:'userManager/creat',
              data:{
                id:_self.editUserObj.id,
                userCode:_self.editUserObj.userCode,
                userName:_self.editUserObj.userName,
                emil:_self.editUserObj.emil,
                password:_self.editUserObj.password,
                remark:_self.editUserObj.remark,
                status:_self.editUserObj.status
              },
              success:function(res){
                if(res.status == 200){
                  _self.dialogEditUserVisible = false;
                  _self.requestUserList();

                }else{

                }
              }
            })

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      /**
       *  配置用户角色
       */
      submitUserRole:function(formName){
        var _self = this;
        _self.utils.ajaxJSON({
          type:"post",
          url:"userManager/userRole",
          data:_self.userRole,
          success:function(res){
            console.log(res);
            if(res.status == 200){
              _self.dialogUseRoleVisible = false;
              _self.$message({type:"success",message:'配置角色成功'});
            }

          }
        })

      },
      /**
       *  重置表单
       * @param user
       */
      resetForm:function(user){
        this.$refs[user].resetFields();
      },
      /**
       * 配置角色
       */
      addUserRole:function(scope){
        this.userRole.userCode = scope.userCode;
        this.userRole.userId = scope.userId;

        this.dialogUseRoleVisible = true;
      },
      /**
       * 修改用户信息
       */
      editUser:function(scope){
        var _self = this;
        this.dialogEditUserVisible = true;
        _self.editUserObj.id = scope.userId;
        _self.editUserObj.userName = scope.userName;
        _self.editUserObj.emil = scope.email;
        _self.editUserObj.status = scope.status;
        _self.editUserObj.remark = scope.remark;
        _self.editUserObj.userCode = scope.userCode;

      },
      deleteUser:function(scope){

        var  _self = this;
        _self.utils.ajaxJSON({
          type:'POST',
          url:'userManager/delete',
          data:{
            id:scope.userId,
            userCode:scope.userCode
          },
          success:function(res){
            if(res.status == 200){
              _self.requestUserList();
              _self.$message({
                message: '恭喜你，删除成功！',
                type: 'success'
              });
            }else{
              _self.$message({
                message: '恭喜你，删除失败！',
                type: 'error'
              });
            }

          }
        })
      },
      requestUserList:function(){
        var _self = this;
        _self.utils.get({
          type:'get',
          url:'userManager/all',

          success:function(res){
            if(res.status ==200)
              _self.creatUserObj(res.dataList);

          }
        })
      },
      /**
       *  解析数据
       */
      creatUserObj:function(dataArr){
        this.tableData= [];
        for(var i = 0;i < dataArr.length;i++){
          var date = this.getDate(dataArr[i].creatDate);
          console.log(date);
          var obj= {
            userId:dataArr[i].id,
            userCode:dataArr[i].userCode,
            userName:dataArr[i].userName,
            creatDate:date,
            creatBy:dataArr[i].creatBy,
            remark:dataArr[i].remark,
            email:dataArr[i].emil,
            status:dataArr[i].status,
            state:(dataArr[i].status == true ? '是' : '否')

          }
          this.tableData.push(obj);
        }
      },
      getDate:function (longDate) {
          var now = new Date(longDate),
            y = now.getFullYear(),
            m = now.getMonth() + 1,
            d = now.getDate();
       return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " ";// + now.toTimeString().substr(0, 8);
      },

       /**
       * 根据条件查询
       */
      searchUser:function() {
        var _self = this,startTime="",endTime="";
        if(_self.formInline.searchDate.length >0){

           startTime = _self.formInline.searchDate[0].getTime();

           endTime = _self.formInline.searchDate[1].getTime();
        }

        var obj ={
          name:_self.formInline.user,
          email:_self.formInline.email,
          startDate:startTime,
          endDate:endTime
        }

        _self.utils.ajaxJSON({
          type:'POST',
          url:'userManager/search',
          data:obj,
          success:function(res){
            _self.creatUserObj(res.msg);
          }
        })
        console.log(_self.formInline);
      }

		}
	}
</script>
